package com.weixin.paleituo.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.HouseDetailPagerAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.bean.HX;
import com.weixin.paleituo.bean.HouseDetailBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.fragment.SaleHouseFragment;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * Author yichao
 * Time  2017/12/1 9:12
 * Dest  楼盘详情
 */
public class HouseDetailsActivity extends HouseDetailsBaseActivity implements ViewPager.OnPageChangeListener {

    @BindView(R.id.viewpager_activity_house_details)
    ViewPager mViewpagerActivityHouseDetails;
    /*  @BindView(R.id.rt_headroot_activity_house_details)
      RelativeLayout mRtHeadrootActivityHouseDetails;*/
    @BindView(R.id.tv_imageincadtor_activity_house_details)
    TextView mTvImageincadtorActivityHouseDetails;
    @BindView(R.id.tv_price_activity_house_details)
    TextView mTvPriceActivityHouseDetails;
    @BindView(R.id.tv_money_activity_house_details)
    TextView mTvMoneyActivityHouseDetails;
    @BindView(R.id.tv_address_activity_house_details)
    TextView mTvAddressActivityHouseDetails;
    @BindView(R.id.tv_address_details_activity_house_details)
    TextView mTvAddressDetailsActivityHouseDetails;
    @BindView(R.id.tv_kaipan_activity_house_details)
    TextView mTvKaipanActivityHouseDetails;
    @BindView(R.id.tv_time_activity_house_details)
    TextView mTvTimeActivityHouseDetails;
    @BindView(R.id.fl_house_type)
    FrameLayout mFlHouseType;
    @BindView(R.id.tv_jiaotong_activity_details)
    TextView mTvJiaotongActivityDetails;
    @BindView(R.id.rl_bottom_activity_house_details)
    LinearLayout mRlBottomActivityHouseDetails;
    @BindView(R.id.tv_house_sales_status_activity_floorhome)
    TextView mTvHouseSalesStatusActivityFloorhome;
    @BindView(R.id.tv_salehouse)
    TextView mTvSalehouse;
    @BindView(R.id.tv_buyhouse_activity_house_details)
    TextView mTvBuyhouseActivityHouseDetails;
    @BindView(R.id.tv_title_activity_house_details)
    TextView mtvTitle;
    @BindView(R.id.tv_updatetime_activity_house_details)
    TextView mTvUpteTime;
    @BindView(R.id.tv_developer_activity_house_details)
    TextView mTvDeveloperActivityHouseDetails;
    @BindView(R.id.tv_new_open_activity_house_details)
    TextView mTvNewOpenActivityHouseDetails;
    @BindView(R.id.tv_accept_house_time_activity_house_details)
    TextView mTvAcceptHouseTimeActivityHouseDetails;
    @BindView(R.id.tv_property_activity_house_details)
    TextView mTvPropertyActivityHouseDetails;
    @BindView(R.id.tv_licen_activity_huouse_details)
    TextView mTvLicenActivityHuouseDetails;
    @BindView(R.id.tv_intro_activity_house_details)
    TextView mTvIntroActivityHouseDetails;
    @BindView(R.id.tv_environment_activity_house_details)
    TextView mTvEnvironmentActivityHouseDetails;
    @BindView(R.id.tv_peitao_activity_details)
    TextView mTvPeitaoActivityDetails;
    @BindView(R.id.ll_tagsroot_activity_house_details)
    LinearLayout mllTAgsToot;
    @BindView(R.id.mTexturemap)
    TextureMapView mMapView;
    @BindView(R.id.iv_peitao_arrow_activity_details)
    ImageView mIvPeiTao;

    @BindView(R.id.scrollview_root_activity_house_details)
    ScrollView mScrollView;
    @BindView(R.id.iv_jiaoton_arrow_activity_details)
    ImageView mIvJiaoTong;
/*    @BindView(R.id.iv_back_activity_house_details)
    ImageView mIvBackActivityHouseDetails;*/
/*    @BindView(R.id.iv_message_activity_house_details)
    ImageView mIvMessageActivityHouseDetails;*/
    @BindView(R.id.ll_headroot_activity_house_details)
    LinearLayout mLlHeadrootActivityHouseDetails;
    @BindView(R.id.tv_presell_activity_house_details)
    TextView mTvPresellActivityHouseDetails;
    @BindView(R.id.rl_price_root_activity_house_detais)
    RelativeLayout mRlPriceRootActivityHouseDetais;
    private int tagPosition = -1;
    private List<String> mIntegers;
    private HouseDetailPagerAdapter mHouseDetailPagerAdapter;

    private SaleHouseFragment mHouseFragment;
    private LoadingPagerHead mLoadingPagerHead;
    private BaiduMap mMapViewMap;
    private String mHouseId;
    private HouseDetailBean mHouseDetailBean;
    private UiSettings uiSettings;
    private String mCity;
/*
    @Override
    protected void initView() {
        mLoadingPager = new LoadingPager(this,1) {
            @Override
            protected void close() {
                finish();
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(HouseDetailsActivity.this, R.layout.activity_house_details);
            }

            @Override
            protected void reLoading() {
                retryLoading();

            }
        };
       // UIUtils.inflate(HouseDetailsActivity.this, R.layout.activity_house_details);
        setContentView(mLoadingPager);

    }*/

    /**
     * 设置属性
     *
     * @param data
     */

    private void setHouseData(HouseDetailBean data) {
        mHouseId = data.getId() + "";
        mCity = data.getCity();

        mtvTitle.setText(data.getHouses() + "");
      //  mTvMoneyActivityHouseDetails.setText(data.getMoney() + "");
        //   mTvUpteTime.setText(data.getUpdate_time() + "更新");
        mTvTimeActivityHouseDetails.setText(data.getDate());
        mTvAddressDetailsActivityHouseDetails.setText(data.getAddress());
        mTvDeveloperActivityHouseDetails.setText(data.getDeveloper());
        mTvNewOpenActivityHouseDetails.setText(data.getDate());
        mTvAcceptHouseTimeActivityHouseDetails.setText(data.getRoom_time());
        mTvPropertyActivityHouseDetails.setText(data.getProperty() + "");
        mTvLicenActivityHuouseDetails.setText(data.getLicence());

        mTvIntroActivityHouseDetails.setText(data.getSummary());
        mTvEnvironmentActivityHouseDetails.setText(data.getPeriphery() + "");
        mTvJiaotongActivityDetails.setText(data.getTraffic());


        int soldStatus = data.getSoldStatus();
        if (soldStatus == Contans.HOUSE_ONSALE_TYPE) {
            mTvBuyhouseActivityHouseDetails.setFocusable(true);
            mTvBuyhouseActivityHouseDetails.setFocusableInTouchMode(true);
            mTvBuyhouseActivityHouseDetails.setEnabled(true);
            mTvPresellActivityHouseDetails.setVisibility(View.GONE);
                    mRlPriceRootActivityHouseDetais.setVisibility(View.VISIBLE);
          //  mTvMoneyActivityHouseDetails
            UIUtils.showPrice(soldStatus,mTvMoneyActivityHouseDetails,data.getMoney());
            mTvHouseSalesStatusActivityFloorhome.setVisibility(View.VISIBLE);
        } else {
            mTvBuyhouseActivityHouseDetails.setFocusableInTouchMode(false);
            mTvBuyhouseActivityHouseDetails.setFocusable(false);
            mTvBuyhouseActivityHouseDetails.setEnabled(false);
            mTvPresellActivityHouseDetails.setVisibility(View.VISIBLE);
            mRlPriceRootActivityHouseDetais.setVisibility(View.GONE);
            UIUtils.showPrice(soldStatus,mTvPresellActivityHouseDetails,data.getMoney());
            mTvHouseSalesStatusActivityFloorhome.setVisibility(View.GONE);
            UIUtils.showPrice(soldStatus,mTvBuyhouseActivityHouseDetails,"");
        }


/*        mTvJiaotongActivityDetails.post(new Runnable() {
            @Override
            public void run() {
                int lineCount = mTvJiaotongActivityDetails.getLineCount();
                LogUtils.i(TAG, "交通显示文字行数：：" + lineCount);

                if (lineCount > 2) {

                    mIvJiaoTong.setVisibility(View.VISIBLE);
                    mTvJiaotongActivityDetails.setMaxLines(2);
                } else {
                    mIvJiaoTong.setVisibility(View.INVISIBLE);

                }
            }
        });*/
/*
        mTvPeitaoActivityDetails.post(new Runnable() {
            @Override
            public void run() {
                if (mTvPeitaoActivityDetails.getLineCount() > 3) {
                    mIvPeiTao.setVisibility(View.VISIBLE);
                    mTvPeitaoActivityDetails.setMaxLines(3);
                } else {
                    mIvPeiTao.setVisibility(View.INVISIBLE);

                }
            }
        });*/

        mTvPeitaoActivityDetails.setText(data.getDeploy());
        List<String> tags = data.getTags();
        if (tags != null && tags.size() != 0) {
            for (String tag : tags) {
                if (!StringUtils.isEmpty(tag)) {
                    tagPosition++;
                    if (tagPosition <= 2) {
                        TextView textView = new TextView(this);
                        if (tagPosition == 0) {

                            textView.setTextColor(UIUtils.getColor(R.color.c_ff37f4c5));
                            textView.setBackgroundResource(R.drawable.tag_1_shape);

                        } else if (tagPosition == 1) {
                            textView.setTextColor(UIUtils.getColor(R.color.c_25a6e9));
                            textView.setBackgroundResource(R.drawable.tag_2_shape);
                            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            layoutParams.setMargins(UIUtils.dip2px(7), 0, 0, 0);

                            textView.setLayoutParams(layoutParams);

                        } else if (tagPosition == 2) {
                            textView.setTextColor(UIUtils.getColor(R.color.c_d84cfb));
                            textView.setBackgroundResource(R.drawable.tag_3_shape);
                            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            layoutParams.setMargins(UIUtils.dip2px(7), 0, 0, 0);
                            textView.setLayoutParams(layoutParams);
                        }

                        textView.setPadding(UIUtils.dip2px(2), UIUtils.dip2px(0), UIUtils.dip2px(2), UIUtils.dip2px(0));
                        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, UIUtils.px2dip(UIUtils.getDimens(R.dimen.sp_10)));
                        textView.setGravity(Gravity.CENTER);
                        textView.setText(tag);
                        mllTAgsToot.addView(textView);
                    }

                  /*  TextView textView=new TextView(this);
                    LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    layoutParams.setMargins(UIUtils.dip2px(15),0,0,0);
                    textView.setLayoutParams(layoutParams);
                    textView.setPadding(UIUtils.dip2px(5),UIUtils.dip2px(2),UIUtils.dip2px(5),UIUtils.dip2px(2));
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
                    textView.setTextColor(UIUtils.getColor(R.color.c_FDA444));
                    textView.setBackgroundColor(UIUtils.getColor(R.color.c_fffce2c5));
                    textView.setGravity(Gravity.CENTER);
                    textView.setText(tag);
                    mllTAgsToot.addView(textView);*/


                }


            }


        }


        //设置定位
        if (!StringUtils.isEmpty(data.getLatitude() + "") && !StringUtils.isEmpty(data.getLongitude() + "")) {
          /*  // 开启定位图层
            mMapViewMap.setMyLocationEnabled(true);
            // 构造定位数据
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(40)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(data.getLatitude())
                    .longitude(data.getLongitude()).build();

            // 设置定位数据
            mMapViewMap.setMyLocationData(locData);*/
            //定义Maker坐标点

            LatLng point = new LatLng(data.getLatitude(), data.getLongitude());

            //构建Marker图标

            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(R.mipmap.select_house);

            //构建MarkerOption，用于在地图上添加Marker

            OverlayOptions option = new MarkerOptions()
                    .position(point)
                    .icon(bitmap);

            //在地图上添加Marker，并显示

            mMapViewMap.addOverlay(option);
            LatLng points = new LatLng(data.getLatitude(), data.getLongitude());

            mMapViewMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point));

        }

    }


    @Override
    protected void initData() {
        //    initFragment();
        super.initData();
        mIntegers = new ArrayList<>();
        mMapViewMap = mMapView.getMap();
        mMapView.showZoomControls(false);

        uiSettings = mMapViewMap.getUiSettings();
        uiSettings.setZoomGesturesEnabled(false);
        uiSettings.setScrollGesturesEnabled(false);
        uiSettings.setRotateGesturesEnabled(false);
        mHouseDetailPagerAdapter = new HouseDetailPagerAdapter(this, mIntegers);
        mViewpagerActivityHouseDetails.setAdapter(mHouseDetailPagerAdapter);
        retryLoading();
        initBaiduMap();
        BaiduMap.OnMapClickListener listener = new BaiduMap.OnMapClickListener() {
            /**
             * 地图单击事件回调函数
             * @param point 点击的地理坐标
             */
            public void onMapClick(LatLng point) {
                if (!StringUtils.isEmpty(mCity)) {
                    //跳转到地图
                    LatLng latLng = new LatLng(mHouseDetailBean.getLatitude(), mHouseDetailBean.getLongitude());
                    LocationMapActivity.startActivity(HouseDetailsActivity.this, mCity, false, latLng);
                }
            }

            /**
             * 地图内 Poi 单击事件回调函数
             * @param poi 点击的 poi 信息
             */
            public boolean onMapPoiClick(MapPoi poi) {


                return false;
            }
        };
        mMapViewMap.setOnMapClickListener(listener);


    }

    @Override
    protected View getContentView(HouseDetailsBaseActivity houseDetailsBaseActivity) {


        mLoadingPagerHead = new LoadingPagerHead(this,0,1) {
            @Override
            protected void close() {
                finish();
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(HouseDetailsActivity.this, R.layout.activity_house_details);
            }

            @Override
            protected void reLoading() {
                retryLoading();

            }
        };
        return mLoadingPagerHead;
    }

    /**
     * 配置百度地图
     */
    private void initBaiduMap() {
/*
        BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.mipmap.select_house);
        MyLocationConfiguration myLocationConfiguration = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING,
                false,
                mCurrentMarker,
                0xAAFFFF88,
                0xAA00FF00);

        mMapViewMap.setMyLocationConfiguration(myLocationConfiguration);*/

    }

    /**
     * 初始化加载
     */
    private void retryLoading() {
        String houserId = getIntent().getStringExtra(Contans.INTENT_DATA);
        Observable<StatusCode<HouseDetailBean>> houseDetails = ApiUtils.getApi().getHouseDetails(houserId);
        HttpUtil.getInstance().toSubscribe(houseDetails, new ProgressSubscriber<HouseDetailBean>(this) {


            @Override
            protected void _onNext(StatusCode<HouseDetailBean> t) {
                HouseDetailBean houseDetailBean = t.getData();
                if (houseDetailBean != null) {
                    mHouseDetailBean = houseDetailBean;
                    setHouseData(houseDetailBean);
                    //设置轮播
                    List<String> bannersList = houseDetailBean.getBannersList();
                    if (bannersList != null && bannersList.size() > 0) {
                        mIntegers.clear();
                        mIntegers.addAll(bannersList);
                        mTvImageincadtorActivityHouseDetails.setText(1 + "/" + mIntegers.size());
                        mHouseDetailPagerAdapter.notifyDataSetChanged();
                    }
                    //在售户型
                    List<HX> hxList = houseDetailBean.getHXList();
                    if (hxList != null && hxList.size() != 0) {
                        initFragment(hxList);
                        mTvSalehouse.setTextColor(getResources().getColor(R.color.c_ff383838));
                        mTvSalehouse.setText("在售户型(" + hxList.size() + ")");
                    }
                    mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                } else {
                    mLoadingPagerHead.showPagerView(Contans.STATE_EMPTY);
                }
            }

            @Override
            protected void _onError(String message) {

                LogUtils.e(TAG, "楼盘详情 ：" + message);
                mLoadingPagerHead.showPagerView(Contans.STATE_ERROR);

                if (Contans.HOUSE_SOLD_OUT.equalsIgnoreCase(message)){
                    mLoadingPagerHead.showPagerView(Contans.STATE_SOLDOUT);
                }else {
                    ToastUtils.makeText(message);
                }

            }
        }, "hxdetails", lifecycleSubject, false, true);
    }


    public static void startActivity(Context context, String houseId) {
        Intent intent = new Intent(context, HouseDetailsActivity.class);
        intent.putExtra(Contans.INTENT_DATA, houseId);
        context.startActivity(intent);
    }

    @Override
    protected void initEvent() {
        mViewpagerActivityHouseDetails.addOnPageChangeListener(this);

        mMapView.getChildAt(0).setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    mScrollView.requestDisallowInterceptTouchEvent(false);
                } else {
                    mScrollView.requestDisallowInterceptTouchEvent(true);
                }
                return false;
            }
        });

    }

    @Override
    protected void onDestroy() {
        if (mMapViewMap != null) {
            mMapViewMap.clear();
        }
        if (mMapView != null) {
            mMapView.onDestroy();
        }
        super.onDestroy();
    }

    /**
     * 显示房屋类型
     *
     * @param hxList
     */
    private void initFragment(List<HX> hxList) {
        //  mHouseFragment = new SaleHouseFragment(1);
        //   mSaleShopFragment = new SaleShopFragment(2);
        mHouseFragment = SaleHouseFragment.newInstance((ArrayList<HX>) hxList, 1);
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
     /*   fragmentTransaction.add(R.id.fl_house_type, mHouseFragment, "salehouse").show(mHouseFragment)
                .add(R.id.fl_house_type, mSaleShopFragment, "sakeshop").hide(mSaleShopFragment).commit();*/
        fragmentTransaction.add(R.id.fl_house_type, mHouseFragment, "salehouse").show(mHouseFragment).commit();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mTvImageincadtorActivityHouseDetails.setText(position + 1 + "/" + mIntegers.size());
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @OnClick(R.id.tv_house_sales_status_activity_floorhome)
    public void onMTvHouseSalesStatusActivityFloorhomeClicked() {

        if (StringUtils.isEmpty(mHouseId)) {
            return;
        }
        SaleStatusActivity.startActivity(this, mHouseId);
    }

    @OnClick(R.id.tv_salehouse)
    public void onMTvSalehouseClicked() {
        //售房
        //    mTvSaleshop.setTextColor(getResources().getColor(R.color.c_ff999999));
        FragmentManager supportFragmentManager1 = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager1.beginTransaction();
        fragmentTransaction.show(mHouseFragment).commit();
    }

    @OnClick(R.id.tv_buyhouse_activity_house_details)
    public void onTvBuyHouseClicked() {
        if (BaseApplication.isLoginSuccess) {
            if (mHouseDetailBean != null) {
                if (mHouseDetailBean.getLotNumber() == 0) {
                    //   SaleStatusActivity
                    LeaseHouseActivity.startActivity(this, mHouseId);

                } else if (mHouseDetailBean.getLotNumber() == 1) {
                    LotteryBuyHouseActivity.startActivity(this, mHouseId);
                }
            }


        } else {
            LoginActivity.startActivity(this, true);
        }

    }

    public boolean isShowAllJiaoTon = false;

    /**
     * 显示交通文字是否全部
     */
    @OnClick(R.id.iv_jiaoton_arrow_activity_details)
    public void onIvJiaotongArrowClicked() {

        if (isShowAllJiaoTon) {
            //目前显示全部
            isShowAllJiaoTon = false;
            mIvJiaoTong.setImageResource(R.mipmap.xiangxia);
            mTvJiaotongActivityDetails.setMaxLines(2);
        } else {
            isShowAllJiaoTon = true;
            mIvJiaoTong.setImageResource(R.mipmap.xiangshang);
            mTvJiaotongActivityDetails.setMaxLines(100);
        }

    }

    private boolean isShowPeiTao = false;

    @OnClick(R.id.iv_peitao_arrow_activity_details)
    public void onIvPeiTaoArrowClicked() {

        if (isShowAllJiaoTon) {
            //目前显示全部
            isShowAllJiaoTon = false;
            mIvPeiTao.setImageResource(R.mipmap.xiangxia);
            mTvPeitaoActivityDetails.setMaxLines(3);
        } else {
            isShowAllJiaoTon = true;
            mIvPeiTao.setImageResource(R.mipmap.xiangshang);
            mTvPeitaoActivityDetails.setMaxLines(100);
        }

    }

/*    @OnClick(R.id.iv_back_activity_house_details)
    public void onMIvBackActivityHouseDetailsClicked() {
        finish();
    }*/

  /*  @OnClick(R.id.iv_message_activity_house_details)
    public void onMIvMessageActivityHouseDetailsClicked() {

        if (BaseApplication.isLoginSuccess) {

            MyMessageActivity.startActivity(this, BaseApplication.getUserId());
        } else {
            LoginActivity.startActivity(this, true);
        }
    }*/

}
